<template>
  <div v-if="open" class="fixed inset-0 bg-black/40 grid place-items-center p-4 z-50">
    <div class="card w-full max-w-lg">
      <div class="text-lg font-semibold mb-2">{{ isEditMode ? '编辑尿布记录' : '记录尿布' }}</div>
      <form class="space-y-3" @submit.prevent="save">
        <label class="block">
          <span class="text-sm">时间</span>
          <input class="input mt-1" type="datetime-local" v-model="formTimeLocal" />
        </label>
        <label class="block">
          <span class="text-sm">类型</span>
          <select class="input mt-1" v-model="diaperType">
            <option value="WET">清尿</option>
            <option value="DIRTY">便便</option>
            <option value="MIXED">混合</option>
          </select>
        </label>
        <label class="block">
          <span class="text-sm">备注</span>
          <textarea class="input mt-1" rows="3" placeholder="可输入备注...（可选）" v-model="note" />
        </label>
        <div class="flex justify-end gap-2">
          <button type="button" class="px-4 py-2 rounded bg-bg" @click="emit('update:open', false)">取消</button>
          <button class="btn-primary" type="submit">保存</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useUserStore } from '../stores/user';
import { API_CONFIG } from '../services/api';

// 临时解决方案：直接定义函数
async function createDiaper(payload: any) {
  const token = localStorage.getItem('auth_token');
  console.log('DiaperModal createDiaper - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/diaper`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

async function updateDiaper(payload: any) {
  const token = localStorage.getItem('auth_token');
  console.log('DiaperModal updateDiaper - token:', token);
  const resp = await fetch(`${API_CONFIG.BASE_URL}/api/records/diaper/${payload.id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token || ''}`
    },
    body: JSON.stringify(payload)
  });
  if (!resp.ok) {
    const errorText = await resp.text();
    throw new Error(`HTTP ${resp.status}: ${errorText}`);
  }
  return await resp.json();
}

const props = defineProps<{ 
  open: boolean;
  editData?: any; // 编辑时的数据
}>();
const emit = defineEmits<{ 
  (e: 'update:open', v: boolean): void;
  (e: 'saved'): void;
}>();
const userStore = useUserStore();

const diaperType = ref<'WET' | 'DIRTY' | 'MIXED'>('WET');
const note = ref('');
const formTimeLocal = ref('');
const isEditMode = computed(() => !!props.editData);

watch(
  () => props.open,
  (v) => {
    if (v) {
      if (props.editData) {
        // 编辑模式：填充现有数据
        const editTime = new Date(props.editData.eventTime);
        formTimeLocal.value = new Date(editTime.getTime() - editTime.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        diaperType.value = props.editData.diaperType;
        note.value = props.editData.note || '';
      } else {
        // 新建模式：使用当前时间
        const now = new Date();
        formTimeLocal.value = new Date(now.getTime() - now.getTimezoneOffset() * 60000)
          .toISOString()
          .slice(0, 16);
        // 重置表单
        diaperType.value = 'WET';
        note.value = '';
      }
    }
  }
);

const eventTime = computed(() => new Date(formTimeLocal.value).toISOString());

async function save() {
  if (!userStore.currentBabyId) {
    alert('请先选择宝宝');
    return;
  }
  
  try {
    if (isEditMode.value) {
      // 编辑模式：调用更新API
      await updateDiaper({
        id: props.editData.id,
        babyId: userStore.currentBabyId,
        eventTime: eventTime.value,
        diaperType: diaperType.value,
        note: note.value || undefined
      });
    } else {
      // 新建模式：调用创建API
      await createDiaper({
        babyId: userStore.currentBabyId,
        eventTime: eventTime.value,
        diaperType: diaperType.value,
        note: note.value || undefined
      });
    }
    
    emit('saved');
    emit('update:open', false);
  } catch (error) {
    console.error('保存尿布记录失败:', error);
    alert('保存失败，请重试');
  }
}
</script>

<style scoped></style>